package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @description: 原理：使用redis的自增长类型，实现自增长的id
 * @author: Administrator
 * @date: Created in 2021/2/25 17:14
 * @version: 0.0.1
 * @modified By:
 */
@Service
public class IdService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //生成自增长的id
    public Long createId(String type,String objectId) {
        type= StringUtils.upperCase(type);
        String hashKey="TANHUA_HASH_ID_"+type;
        if(this.redisTemplate.opsForHash().hasKey(hashKey,objectId)){
            return Long.valueOf(this.redisTemplate.opsForHash().get(hashKey,objectId).toString());
        }
        String key="TANHUAN_ID_"+type;
        Long id = this.redisTemplate.opsForValue().increment(key);
        //将生成的id写入到hash表中
        this.redisTemplate.opsForHash().put(hashKey,objectId,id.toString());
        return id;
    }
}
